/**
 * Created by Nguyen Duc Thinh on 4/6/2015.
 */
// config/passport.js

// load all the things we need
var LocalStrategy = require('passport-local').Strategy;

// load up the user models
//var User = require('../app/models/user');
var simpleUsers = [{
    email: "nguyenducthinhdl@gmail.com", password: "thinh123"
}, {
    email: "cuongnm@gmail.com", password: "cuong123"
}];

// Data Store users
var oUsers = [];
for(var i = 0; i < simpleUsers.length; i++){
    oUsers[i] = simpleUsers[i];
    oUsers[i].id = i;
    oUsers[i].validPassword = function(password){
        return password === this.password;
    }
}

// User's model
var User = {
    findById: function(id, done){
        for(var i = 0; i < oUsers.length; i++){
            if (oUsers[i].id === id){
                return done(null, oUsers[i]);
                break;
            }
        }
        return done(null, null);
    },
    findOne: function(email, done){
        for(var i = 0; i < oUsers.length; i++){
            if (oUsers[i].email === email['local.email']){
                return done(null, oUsers[i]);
                break;
            }
        }
        return done(null, null);
    },
    addOne: function(email, password){
        var newUser = {
            id: oUsers.length,
            email: email,
            password: password,
            validPassword: function(password){
                return password === this.password;
            }
        }
        oUsers.push(newUser);
        return newUser;
    }
};

// expose this function to our app using module.exports
module.exports = function (passport) {

    // =========================================================================
    // passport session setup ==================================================
    // =========================================================================
    // required for persistent login sessions
    // passport needs ability to serialize and unserialize users out of session

    // used to serialize the user for the session
    passport.serializeUser(function (user, done) {
        done(null, user.id);
    });

    // used to deserialize the user
    passport.deserializeUser(function (id, done) {
        User.findById(id, function (err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-signup', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback: true // allows us to pass back the entire request to the callback
        },
        function (req, email, password, done) {

            // asynchronous
            // User.findOne wont fire unless data is sent back
            process.nextTick(function () {
                // find a user whose email is the same as the forms email
                // we are checking to see if the user trying to login already exists
                User.findOne({'local.email': email}, function (err, user) {
                    // if there are any errors, return the error
                    if (err)
                        return done(err);

                    // check to see if theres already a user with that email
                    if (user) {
                        return done(null, false, req.flash('signupMessage', 'That email is already taken.'));
                    } else {

                        // if there is no user with that email
                        // create the user
                        var newUser = User.addOne(email, password);
                        if (newUser){
                            return done(null, newUser);
                        }
                        else{
                            return done('Can not insert new user');
                        }
                    }
                });
            });
        }));

    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use('local-login', new LocalStrategy({
            // by default, local strategy uses username and password, we will override with email
            usernameField : 'email',
            passwordField : 'password',
            passReqToCallback : true // allows us to pass back the entire request to the callback
        },
        function(req, email, password, done) { // callback with email and password from our form
            //return done(null, false, req.flash('loginMessage', 'No user found.'));
            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ 'local.email' :  email }, function(err, user) {
                // if there are any errors, return the error before anything else
                if (err)
                    return done(err);

                // if no user is found, return the message
                if (!user)
                    return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash

                // if the user is found but the password is wrong
                if (!user.validPassword(password))
                    return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata

                // all is well, return successful user
                return done(null, user);
            });

        }));
};